package deviceScript

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Number"
	"go-fox-edge-device/deviceModel"
	"reflect"
	"sync"
)

type ScriptEngineModel struct {
	mutex    sync.Mutex
	modelMap map[string]interface{}
}

func (e *ScriptEngineModel) setEnvDeviceModel(routineKey string, manufacturer string, deviceType string, modelNameKey string, params map[string]interface{}) {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	scriptEngine := engineService.getScriptEngine(manufacturer, deviceType, routineKey)

	// 检测：是否定义了该字段
	if Method.HasEmpty(modelNameKey) {
		return
	}

	if params == nil {
		return
	}

	// 从用户的输入参数中，取出设备模型名称
	modelName := params[modelNameKey]
	if Method.HasEmpty(modelName) {
		return
	}

	// 检查是否为字符串
	if reflect.TypeOf(modelName).Kind() != reflect.String {
		return
	}

	// 取出全局的设备模型
	globalModel := deviceModel.GetDeviceModels(modelName.(string))
	if Method.HasEmpty(globalModel) {
		return
	}

	// 从引擎侧，取出合并设备模型
	model, _ := Map.GetValue(e.modelMap, manufacturer, deviceType, modelName)
	if model != nil {
		globalUpdateTime := Map.GetOrDefault(globalModel, "updateTime", float64(0))
		engineUpdateTime := Map.GetOrDefault(model.(map[string]interface{}), "updateTime", float64(0))
		if Number.MakeInt64(globalUpdateTime) == Number.MakeInt64(engineUpdateTime) {
			return
		}
	}

	// 保存模型级别的数据
	model = globalModel
	Map.SetValue(e.modelMap, manufacturer, deviceType, modelName, model)

	// 构造跟该型号设备相关的的设备模型信息
	deviceModels := e.buildEngineModels(manufacturer, deviceType)
	if deviceModels == nil {
		return
	}

	// 将模型信息注入到引擎之中
	err := scriptEngine.Set("fox_edge_model", deviceModels)
	if err != nil {
		return
	}
}

func (e *ScriptEngineModel) buildEngineModels(manufacturer string, deviceType string) map[string]interface{} {
	// 取出整个设备类型级别的数据
	m, err := Map.GetValue(e.modelMap, manufacturer, deviceType)
	if err != nil {
		return nil
	}

	engineModels := m.(map[string]interface{})

	result := make(map[string]interface{})
	for key, value := range engineModels {
		engineModel := value.(map[string]interface{})

		// 取出其中的modelParam
		modelParam := engineModel["modelParam"]
		if modelParam == nil {
			continue
		}

		list := modelParam.(map[string]interface{})["list"]
		if list == nil {
			continue
		}

		result[key] = list
	}

	return result
}
